﻿using System;
using RabbitMQ.Client.MessagePatterns;
using smp.RabbitMq.Strategies;

namespace smp.RabbitMq
{
    internal class ResponderSubscriber : RabbitMqBusBase, IResponderSubscriber
    {
        private readonly ResponderHandlers _handlers;
        private readonly IResponderStrategy _strategy;

        internal ResponderSubscriber(IRabbitMqConfiguration configuration, ResponderHandlers handlers, IResponderStrategy strategy)
            : base(configuration)
        {
            _handlers = handlers;
            _strategy = strategy;
        }

        ~ResponderSubscriber()
        {
            Dispose(false);
        }

        #region Implementation of IDisposable

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion

        #region Implementation of IResponderSubscriber

        public void HostResponderServer()
        {
            while(true)
            {
                try
                {
                    Log.Debug("Responder declaring subscription to queue.");
                    var subscription = new Subscription(Channel, Configuration.Queue);

                    Log.Debug("Initialising Responder server");
                    using (var responseServer = new ResponderServer(subscription, _handlers, _strategy, this, Log))
                    {
                        responseServer.MainLoop();
                    }
                }
                catch (Exception ex)
                {
                    var error = new Exception("Responder failed when trying to subscribe to queue {0} " + Configuration.Queue, ex);
                    Log.Fatal(error);
                    throw error;
                }
            }
        }

        #endregion
    }
}
